package cn.sh.ideal.yedis.builder;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import cn.sh.ideal.yedis.util.Assert;
import cn.sh.ideal.yedis.util.StringUtil;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.Protocol;

/**
 * redis sentinel 客户端的builder
 * Created by wyy
 */
public class RedisSentinelBuilder extends BaseBuilder<JedisSentinelPool>{
    
    private String masterName;
    
    public RedisSentinelBuilder() {}

    public RedisSentinelBuilder(String sentinels,String masterName) {
    	this.nodeStr = sentinels;
    	this.masterName = masterName;
    }
    
    public RedisSentinelBuilder(String sentinels,String masterName,JedisPoolConfig poolConfig) {
    	this.nodeStr = sentinels;
    	this.masterName = masterName;
    	this.poolConfig = poolConfig;
    }

    public JedisSentinelPool build() {
        if (pool == null) {
            while (true) {
                try {
                    LOCK.tryLock(10, TimeUnit.MILLISECONDS);
                    if (pool == null) {
                    	Assert.notEmpty(nodeStr, "sentinels info must be not empty");
                    	Assert.notEmpty(masterName, "masterName info must be not empty");
                        Set<String> sentinelSet = new HashSet<String>();
                        for (String sentinelStr : nodeStr.split(SEPERATOR_NODE)) {
                            String[] sentinelArr = sentinelStr.split(SEPERATOR_IP_PROT);
                            if (sentinelArr.length == 2) {
                                sentinelSet.add(sentinelStr);
                            }
                        }
                        
                        if (StringUtil.isEmpty(password)) {
                        	pool = new JedisSentinelPool(masterName, sentinelSet, poolConfig, timeout, soTimeout, null, Protocol.DEFAULT_DATABASE);
                        } else {
                        	pool = new JedisSentinelPool(masterName, sentinelSet, poolConfig, timeout, soTimeout, password, Protocol.DEFAULT_DATABASE);
                        }
                        
                        return pool;
                    }
                } catch (Throwable e) {//容错
                    logger.error("error in build", e);
                    break;
                } finally {
                    LOCK.unlock();
                }
            }
        }
        return pool;
    }

	public void setMasterName(String masterName) {
		this.masterName = masterName;
	}
}
